using System;
using System.Globalization;

namespace ICP_MS.Plugin.LA300;

public class FormatPercent : ICustomFormatter, IFormatProvider
{
	private static NumberFormatInfo numberformat = new NumberFormatInfo
	{
		NumberDecimalDigits = 3,
		NumberDecimalSeparator = ".",
		NaNSymbol = "###",
		NegativeInfinitySymbol = "---",
		PositiveInfinitySymbol = "+++"
	};

	public object GetFormat(Type formatType)
	{
		if (formatType == typeof(ICustomFormatter))
		{
			return this;
		}
		return null;
	}

	public string Format(string format, object arg, IFormatProvider formatProvider)
	{
		if (arg.GetType() != typeof(double))
		{
			return "!" + arg.ToString();
		}
		double val = (double)arg;
		if (double.IsNaN(val))
		{
			return "***";
		}
		if (val < 0.0)
		{
			return "";
		}
		val *= 100.0;
		if (val < 0.0)
		{
			val = 0.0;
		}
		return val.ToString("0.00", numberformat) + "%";
	}

	public static string Format(object val)
	{
		return new FormatPercent().Format(null, val, null);
	}
}
